package com.mars.admin.modules.post.service.impl;

import com.mars.admin.modules.base.service.impl.BaseServiceImpl;
import com.mars.admin.modules.post.entity.PostComment;
import com.mars.admin.modules.post.mapper.PostCommentMapper;
import com.mars.admin.modules.post.mapper.PostMapper;
import com.mars.admin.modules.post.service.IPostCommentService;
import com.mars.admin.modules.post.vo.PostConmentVO;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

import static com.mars.admin.modules.post.entity.table.PostCommentTableDef.POST_COMMENT;

/**
 * 帖子评论服务实现类
 *
 * @author Mars
 * @version 1.0
 * @date 2025-01-07
 */
@Slf4j
@Service
public class PostCommentServiceImpl extends BaseServiceImpl<PostComment> implements IPostCommentService {

    @Autowired
    private PostCommentMapper postCommentMapper;
    
    @Autowired
    private PostMapper postMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean publishComment(PostComment comment) {
        try {
            // 设置默认值
            if (comment.getLikeCount() == null) {
                comment.setLikeCount(0);
            }
            if (comment.getReplyCount() == null) {
                comment.setReplyCount(0);
            }
            if (comment.getIsTop() == null) {
                comment.setIsTop(0);
            }
            if (comment.getStatus() == null) {
                comment.setStatus(1);
            }

            boolean saved = save(comment);
            if (saved) {
                // 更新帖子评论数
                postMapper.updatePostStats(comment.getPostId(), 0, 0, 1, 0, 0);
                
                // 如果是回复评论，更新父评论的回复数
                if (comment.getParentId() != null) {
                    postCommentMapper.updateReplyCount(comment.getParentId(), 1);
                }
            }
            
            return saved;
        } catch (Exception e) {
            log.error("发布评论失败，评论信息：{}", comment, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean replyComment(PostComment comment, Long parentId, Long replyUserId) {
        try {
            comment.setParentId(parentId);
            comment.setReplyUserId(replyUserId);
            return publishComment(comment);
        } catch (Exception e) {
            log.error("回复评论失败，评论信息：{}，父评论ID：{}，被回复用户ID：{}", comment, parentId, replyUserId, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteComment(Long commentId) {
        try {
            PostComment comment = getById(commentId);
            if (comment == null) {
                return false;
            }
            
            boolean deleted = removeById(commentId);
            if (deleted) {
                // 更新帖子评论数
                postMapper.updatePostStats(comment.getPostId(), 0, 0, -1, 0, 0);
                
                // 如果是回复评论，更新父评论的回复数
                if (comment.getParentId() != null) {
                    postCommentMapper.updateReplyCount(comment.getParentId(), -1);
                }
                
                // 删除子评论（如果有的话）
                // 这里可以选择级联删除或者标记删除
                // 为了数据完整性，这里选择标记删除
                List<PostComment> childComments = postCommentMapper.selectByParentId(commentId, new Page<>(1, Integer.MAX_VALUE)).getRecords();
                for (PostComment childComment : childComments) {
                    childComment.setStatus(2); // 标记为已删除
                    updateById(childComment);
                }
            }
            
            return deleted;
        } catch (Exception e) {
            log.error("删除评论失败，评论ID：{}", commentId, e);
            throw e;
        }
    }

    @Override
    public Page<PostComment> getCommentsByPostId(Long postId, Page<PostComment> page) {
        try {
            return postCommentMapper.selectByPostId(postId, page);
        } catch (Exception e) {
            log.error("根据帖子ID查询评论列表失败，帖子ID：{}", postId, e);
            throw e;
        }
    }

    @Override
    public Page<PostComment> getCommentsByUserId(Long userId, Page<PostComment> page) {
        try {
            return postCommentMapper.selectByUserId(userId, page);
        } catch (Exception e) {
            log.error("根据用户ID查询评论列表失败，用户ID：{}", userId, e);
            throw e;
        }
    }

    @Override
    public Page<PostComment> getCommentsByParentId(Long parentId, Page<PostComment> page) {
        try {
            return postCommentMapper.selectByParentId(parentId, page);
        } catch (Exception e) {
            log.error("根据父评论ID查询子评论列表失败，父评论ID：{}", parentId, e);
            throw e;
        }
    }

    @Override
    public List<PostComment> getHotComments(Long postId, Integer limit) {
        try {
            return postCommentMapper.selectHotComments(postId, limit);
        } catch (Exception e) {
            log.error("查询热门评论失败，帖子ID：{}，限制数量：{}", postId, limit, e);
            throw e;
        }
    }

    @Override
    public List<PostComment> getLatestComments(Long postId, Integer limit) {
        try {
            return postCommentMapper.selectLatestComments(postId, limit);
        } catch (Exception e) {
            log.error("查询最新评论失败，帖子ID：{}，限制数量：{}", postId, limit, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditComment(Long commentId, Integer auditStatus, String auditReason, Long auditUserId) {
        try {
            PostComment comment = new PostComment();
            comment.setId(commentId);
            comment.setUpdateTime(LocalDateTime.now());
            
            // 如果审核通过，设置状态为正常
            if (auditStatus == 1) {
                comment.setStatus(1);
            }
            
            return updateById(comment);
        } catch (Exception e) {
            log.error("审核评论失败，评论ID：{}，审核状态：{}，审核原因：{}", commentId, auditStatus, auditReason, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setCommentTop(Long commentId, Integer isTop) {
        try {
            PostComment comment = new PostComment();
            comment.setId(commentId);
            comment.setIsTop(isTop);
            comment.setUpdateTime(LocalDateTime.now());
            return updateById(comment);
        } catch (Exception e) {
            log.error("设置评论置顶状态失败，评论ID：{}，置顶状态：{}", commentId, isTop, e);
            throw e;
        }
    }

    @Override
    public int countCommentsByPostId(Long postId) {
        try {
            return postCommentMapper.countByPostId(postId);
        } catch (Exception e) {
            log.error("统计帖子的评论数量失败，帖子ID：{}", postId, e);
            throw e;
        }
    }

    @Override
    public int countCommentsByUserId(Long userId) {
        try {
            return postCommentMapper.countByUserId(userId);
        } catch (Exception e) {
            log.error("统计用户的评论数量失败，用户ID：{}", userId, e);
            throw e;
        }
    }

    @Override
    public int countCommentsByParentId(Long parentId) {
        try {
            return postCommentMapper.countByParentId(parentId);
        } catch (Exception e) {
            log.error("统计父评论的子评论数量失败，父评论ID：{}", parentId, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommentLikeCount(Long commentId, Integer increment) {
        try {
            return postCommentMapper.updateLikeCount(commentId, increment) > 0;
        } catch (Exception e) {
            log.error("更新评论点赞数失败，评论ID：{}，增量：{}", commentId, increment, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommentReplyCount(Long commentId, Integer increment) {
        try {
            return postCommentMapper.updateReplyCount(commentId, increment) > 0;
        } catch (Exception e) {
            log.error("更新评论回复数失败，评论ID：{}，增量：{}", commentId, increment, e);
            throw e;
        }
    }

    @Override
    public Page<PostComment> getPendingAuditComments(Page<PostComment> page) {
        try {
            // 这里需要在Mapper中实现查询待审核评论的方法
            // 暂时返回空页面，具体实现需要在Mapper中添加相应方法
            return new Page<>(page.getPageNumber(), page.getPageSize());
        } catch (Exception e) {
            log.error("查询待审核的评论失败", e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteComments(List<Long> commentIds) {
        try {
            return removeByIds(commentIds);
        } catch (Exception e) {
            log.error("批量删除评论失败，评论ID列表：{}", commentIds, e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCommentsByPostId(Long postId) {
        try {
            return postCommentMapper.deleteByPostId(postId) > 0;
        } catch (Exception e) {
            log.error("根据帖子ID删除所有评论失败，帖子ID：{}", postId, e);
            throw e;
        }
    }

    @Override
    public Page<PostConmentVO> pagePostComment(Page<PostConmentVO> page, Long postId, Long userId, Long parentId, Integer status, Integer isTop) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select().from(POST_COMMENT)
                .where(POST_COMMENT.POST_ID.eq(postId))
                .and(POST_COMMENT.IS_DELETED.eq(0));

        if (userId != null) {
            queryWrapper.and(POST_COMMENT.USER_ID.eq(userId));
        }

        // 如果 parentId 为 null，则查询顶级评论；否则查询指定父评论的子评论
        if (parentId != null) {
            queryWrapper.and(POST_COMMENT.PARENT_ID.eq(parentId));
        } else {
            queryWrapper.and(POST_COMMENT.PARENT_ID.isNull());
        }

        if (status != null) {
            queryWrapper.and(POST_COMMENT.STATUS.eq(status));
        }

        if (isTop != null) {
            queryWrapper.and(POST_COMMENT.IS_TOP.eq(isTop));
        }
        // 排序：先按是否置顶降序，再按创建时间降序
        queryWrapper.orderBy(POST_COMMENT.IS_TOP.desc(), POST_COMMENT.CREATE_TIME.desc());

        return postCommentMapper.paginateWithRelationsAs(page,queryWrapper, PostConmentVO.class);
    }

    @Override
    public PostConmentVO getPostCommentWithUserById(Long id) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select().from(POST_COMMENT)
                .where(POST_COMMENT.ID.eq(id));
        return postCommentMapper.selectOneWithRelationsByQueryAs(queryWrapper, PostConmentVO.class);
    }
} 